﻿#include <stdio.h>
#include <easyx.h>
#include <stdlib.h>
#include <time.h>

typedef struct
{
	int x;
	int y;
	int vx;
	int vy;
	COLORREF color;
}ball;

#define NUM 1000
int main()
{
	initgraph(800, 600);
	setorigin(400, 300);
	setaspectratio(1, -1);
	setbkcolor(WHITE);
	cleardevice();
	srand(time(NULL));
	int r = 10;
	ball balls[NUM];
	for (int i = 0; i < NUM; i++)
	{

		int m = -400 + r;
		int n = 400 + r;
		balls[i].x = rand() % (n-m + 1) + m;//圆形的全部都不能超出窗体，为之后的碰撞改变方向做铺垫
		m = -300 + r;
		n = 300 + r;
		balls[i].y = rand() %(n-m + 1) + m;
		m = 5;
		n = 7;
		balls[i].vx = rand() % (n-m + 1) + m;//速度在5~7之间
		if (balls[i].x % 2 == 0)
		{
			balls[i].vx = -balls[i].vx;
		}
		balls[i].vy = rand() % (n-m + 1) + m;//速度在5~7之间
		if (balls[i].y % 2 == 0)
		{
			balls[i].vy = -balls[i].vy;
		}
		balls[i].color = (RGB(rand() % 256, rand() % 256, rand() % 256));
	}
	BeginBatchDraw();
	while (1)//不断地重新绘制更新小球
	{
		cleardevice();
		for (int i = 0; i < NUM; i++)
		{
			setfillcolor(balls[i].color);
			fillcircle(balls[i].x, balls[i].y, r);
		}
		FlushBatchDraw();
		Sleep(40);
		for (int i = 0; i < NUM; i++)
		{
			if (balls[i].y >= 300 - r || balls[i].y <= -300 + r)
			{
				balls[i].vy = -balls[i].vy;
			}
			if (balls[i].x >= 400 - r || balls[i].x <= -400 + r)
			{
				balls[i].vx = -balls[i].vx;
			}
			balls[i].x += balls[i].vx;
			balls[i].y += balls[i].vy;
		}
	}
	EndBatchDraw();
	getchar();
	closegraph();
	return 0;
}

